package HttpServlet;

import Entity.Userinformation;
import Entity.DataDTO3;

import javax.persistence.*;
import javax.sql.DataSource;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.soap.SOAPPart;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.*;
import java.util.stream.Collectors;

@WebServlet(urlPatterns = {"/upload1"})
public class loginservlet extends HttpServlet {
    EntityManager em = Persistence.createEntityManagerFactory("MyJPADemoPU").createEntityManager();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        Userinformation userinformation = em.find(Userinformation.class,username);

        if (userinformation.getUsername().isEmpty()||!(userinformation.getPassword().equals(password))) {
            request.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().println("账号或密码不正确！！请退回上一步继续操作");
        } else {
            HttpSession session = request.getSession(true);
            Map<String, String> map = new HashMap<String, String>();
            map.put("用户名", userinformation.getUsername());
            map.put("密码", userinformation.getPassword());
            map.put("学号", userinformation.getStu_number());
            map.put("手机号码", userinformation.getPhone_number());
            map.put("电子邮箱", userinformation.getEmail());
            map.put("头像", userinformation.getImg());
            //HttpSession session = request.getSession(true);
            Map<String, String> map2 = new HashMap<String, String>();
            DataDTO3 dataDTO3 = userinformation.getDataDTO3();
            if (dataDTO3 != null) {
                map2.put("学号", dataDTO3.getUsername());
                map2.put("姓名", dataDTO3.getName());
                map2.put("学院", dataDTO3.getFaculty_title());
            } else {
                map2.put("提示", "暂时无绑定信息，请前往绑定");
            }
            session.setAttribute("userName", map);
            session.setAttribute("userBone", map2);
            session.setAttribute("token", "not null");

            response.sendRedirect("/show.jsp");
        }
    }
}
